package cn.edu.hqu.javaee.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import cn.edu.hqu.javaee.domain.Order;
import cn.edu.hqu.javaee.domain.User;
import cn.edu.hqu.javaee.repository.OrderRepository;
import cn.edu.hqu.javaee.repository.UserRepository;

@Controller
@RequestMapping("/orders")
@SessionAttributes("order")
public class OrderController {
	private OrderRepository orderRepo;
	private UserRepository userRepo;
	public OrderController(OrderRepository orderRepo,UserRepository userRepo) {
		this.orderRepo = orderRepo;
		this.userRepo=userRepo;
	}

	@GetMapping("/current")
	public String orderFrom(Model model) {
		List<User> user = new ArrayList<>();
		userRepo.findAll().forEach(i -> user.add(i));
		model.addAttribute("user",user);
		System.out.println(user);
		return "orderForm";
	}

	@PostMapping
	public String processOrder(@Valid Order order, Errors errors, SessionStatus sessionStatus, HttpServletRequest request,
            HttpServletResponse response)throws Exception {
		if (errors.hasErrors()) {
			return "orderForm";
		}

		orderRepo.save(order);
		sessionStatus.setComplete();
		formSubmit(request,response);
		return "redirect:/result";
	}
	protected void formSubmit(HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {
	 response.setCharacterEncoding("UTF=8");
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession();
        String values=request.getParameter("name");
        session.setAttribute("name",values);
        values=request.getParameter("number");
        session.setAttribute("number",values);
        values=request.getParameter("year");
        session.setAttribute("year",values);
        values=request.getParameter("major");
        session.setAttribute("major",values);
        values=request.getParameter("college");
        session.setAttribute("college",values);
	    }

}
